const { ProductService } = require("../../services/product_service");

// 引入腾讯地图插件
const citySelector = requirePlugin('citySelector');
var adcode;
var currentPage = 1;
var totalPages = 1;
var totalResults = 0;
const limit = 15;

const key = 'IVGBZ-42JWG-MNPQN-IQOMZ-YUWVO-LVFLI';
const referer = '证件照';

// pages/search/search.js
Page({
  data: {
    selectedCity: "长沙市",
    keyword: '',
    products: []
  },

  onLoad(options) {
    adcode = options.adcode;
    if (typeof options.keyword === 'string') {
      this.getProducts(1);
    }
    this.setData({
      selectedCity: options.city,
    })
  },

  onShow() {
    const selectedCity = citySelector.getCity();
    console.log(selectedCity)
    if (selectedCity != null) {
      adcode = selectedCity.id;
      let city = selectedCity.fullname;
      this.setData({
        selectedCity: city
      })
    }
  },

  chooseCity() {
    wx.navigateTo({
      url: `plugin://citySelector/index?key=${key}&referer=${referer}`,
    })
  },

  onInput(event) {
    this.getProducts(1, true);
  },

  onConfirm(event) {
    this.getProducts(1, true);
  },

  getProducts(page, needClear=false) {
    if (this.data.keyword == '') {
      currentPage = 1;
      this.setData({
        products: []
      })
      return;
    }
    let productService = new ProductService();
    productService.getProductList({
      keyword: this.data.keyword,
      page: page,
      limit: limit,
      adcode: adcode
    }).then(res => {
      currentPage = res.data.page;
      totalPages = res.data.totalPages;
      totalResults = res.data.totalResults;
      if (needClear) {
        this.setData({
          products: res.data.results
        })
      } else {
        this.setData({
          products: this.data.products.concat(res.data.results)
        })
      }
    })
  },

  // 进入商品详情页
  goToDetailPage(event) {
    let index = event.currentTarget.dataset.index;
    let product = this.data.products[index];
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?productId=' + product.id,
    })
  },

  onPullUpLoad() {
    if (currentPage < totalPages) {
      this.getProducts(++currentPage);
    }
  }
})